package com.example.websocket.redis.controller;

import com.example.websocket.redis.config.RedisGroupStreamService;
import com.example.websocket.redis.config.RedisService;
import com.example.websocket.redis.queue.QueueTestListener;
import com.example.websocket.redis.queue.RedisDelayJobService;
import com.example.websocket.websocket.mybatis.dao.UserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("redis")
public class RedisTestController {

//    @Autowired
    private RedisService redisService;

//    @Autowired
    private RedisGroupStreamService redisGroupStreamService;

    @Autowired
    private UserDAO userDAO;

//    @Autowired
    private RedisDelayJobService redisDelayJobService;

    @RequestMapping(value = "addParam", method = RequestMethod.POST)
    public Boolean addParam(@RequestBody Map<String, Object> map) {
        String key = (String) map.get("key");
        List<Object> values = (List<Object>) map.get("values");
        boolean isRunning = redisService.sGetSetSize(key) > 0;
        for (Object o : values) {
            redisService.sSet(key, o);
        }
//        if (!isRunning) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("key", key);
            map1.put("value", redisService.sGet(key).toArray()[0]);
            redisGroupStreamService.sendEvent(map1);
//        }
        return true;
    }

    public void runMethod(String key, String value) {
        System.out.println("正在运行key值为" + key + "中的" + value);
        try {
//            Thread.sleep(10000);
            System.out.println(userDAO.queryTest());
            System.out.println("运行完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            redisService.setRemove(key, value);
            if (redisService.sGetSetSize(key) > 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("key", key);
                map.put("value", redisService.sGet(key).toArray()[0]);
                redisGroupStreamService.sendEvent(map);
            }
        }
    }

    @RequestMapping(value = "queueTest", method = RequestMethod.GET)
    public void queueTest() {
        redisDelayJobService.addQueue("test", 2, TimeUnit.MINUTES, QueueTestListener.class);
    }
}
